package com.demo.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

	// 1.创建realm
		@Bean
		public UserRealm getRealm() {
			return new UserRealm();
		}

	// 2.创建安全管理器
	@Bean
	public SecurityManager getSecurityManager(UserRealm reaml) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(reaml);
		
		//将自定义的会话管理器注册到安全管理器中
		securityManager.setSessionManager(defaultWebSessionManager());
		//将自定义的redis缓存管理器注册到安全管理器中
		securityManager.setCacheManager(cacheManager());
		
		return securityManager;
	}
	
	// 3.创建过滤工厂
	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
		filterFactory.setSecurityManager(securityManager);
		
		filterFactory.setLoginUrl("/autherror?code=1");
		filterFactory.setUnauthorizedUrl("/autherror?code=2");
		return filterFactory;
	}

	//开启对shiro注释的支持
	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(securityManager);
		return advisor;
	}
	
	//从配置文件
	@Value("${spring.redis.host}")
	private String host;
	@Value("${spring.redis.port}")
	private int port;
	
	//1.redis管理器,操作redis
	public RedisManager redisManager() {
		RedisManager redisManager = new RedisManager();
		redisManager.setHost(host);
		redisManager.setPort(port);
		return redisManager;
	}

	//2.sessionDAO
	public RedisSessionDAO redisSessionDAO() {
		RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
		redisSessionDAO.setRedisManager(redisManager());
		return redisSessionDAO;
		
	}
	
	//3.会话管理
	public DefaultWebSessionManager defaultWebSessionManager() {
		CustomSessionManager sessionManager = new CustomSessionManager();
		sessionManager.setSessionDAO(redisSessionDAO());
		return sessionManager;
	}
	
	//4.缓存管理器
	private RedisCacheManager cacheManager() {
		RedisCacheManager redisCacheManager = new RedisCacheManager();
		redisCacheManager.setRedisManager(redisManager());
		return redisCacheManager;
	}
}
